import { reactive } from 'vue'

export const useTableSelection = (tableRef) => {
  const selection = reactive([])

  const onTableSelect = (selectList, row) => {
    const { rowKey } = tableRef.value
    const selected = selectList.findIndex(el => el[rowKey] === row[rowKey]) > -1

    if (selected) {
      selection.push(row)
    } else {
      const index = selection.findIndex(el => el[rowKey] === row[rowKey])
      selection.splice(index, 1)
    }
  }
  const onTableSelectAll = (selectList) => {
    const { rowKey } = tableRef.value

    if (selectList.length) {
      selectList.forEach(row => {
        const is = selection.findIndex(el => el[rowKey] === row[rowKey]) === -1

        if (!is) return

        selection.push(row)
      })
    } else {
      tableRef.value.data.forEach(row => {
        const index = selection.findIndex(el => el[rowKey] === row[rowKey])

        if (index === -1) return

        selection.splice(index, 1)
      })
    }
  }

  return {
    selection,
    onTableSelect,
    onTableSelectAll
  }
}
